package com.qingzhuge.manager.security.filter;

import com.qingzhuge.autoconfigure.QingTingProperties;
import com.qingzhuge.controller.base.AbstractController;
import com.qingzhuge.manager.dto.SecurityUser;
import com.qingzhuge.manager.security.service.UserDetailsServiceImpl;
import com.qingzhuge.manager.security.util.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zeroxiao
 * @date 2019/9/11 09:04
 * JWT验证过滤器
 */
@Slf4j
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private QingTingProperties properties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        final String tokenHeader = request.getHeader(this.properties.getSecurity().getToken());

        if (tokenHeader != null) {
            String username = null;
            String token = null;
            String bearer = properties.getSecurity().getBearer();
            if (StringUtils.isNotBlank(bearer)) {
                if (tokenHeader.startsWith(bearer)) {
                    token = tokenHeader.substring(7);
                }
            } else {
                token = tokenHeader;
            }
            if (StringUtils.isNotBlank(token)) {
                try {
                    username = jwtTokenUtil.getUsername(token);
                } catch (ExpiredJwtException e) {
                    log.error(e.getMessage());
                }
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                SecurityUser userDetails = (SecurityUser) this.userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    AbstractController.setUsername(username);
                    AbstractController.setUid(userDetails.getId());
                }
            }
        }
        chain.doFilter(request, response);
    }
}
